<template>
  <div class="root">
    <div class="center_box">
      <div class="canvas_box">
        <canvas id="myCanvas" width="1600" height="900" ref="myCanvas"></canvas>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";

const myCanvas = ref();
let ctx = null;

// 模拟从服务器获取的图片数据
const imageDataList = [
  {id: 1, name: '星星', url: 'http://172.16.20.72:6700/src/assets/images/photo/1.png', x: 100, y: 100},
  {id: 2, name: '心形', url: 'http://172.16.20.72:6700/src/assets/images/photo/2.png', x: 300, y: 150},
  {id: 3, name: '云朵', url: 'http://172.16.20.72:6700/src/assets/images/photo/3.png', x: 500, y: 200},
  {id: 4, name: '树叶', url: 'http://172.16.20.72:6700/src/assets/images/photo/4.png', x: 200, y: 300},
  {id: 5, name: '水滴', url: 'http://172.16.20.72:6700/src/assets/images/photo/5.png', x: 400, y: 350},
  {id: 6, name: '月亮', url: 'http://172.16.20.72:6700/src/assets/images/photo/6.png', x: 600, y: 100},
  {id: 7, name: '花朵', url: 'http://172.16.20.72:6700/src/assets/images/photo/7.png', x: 100, y: 400},
  {id: 8, name: '蝴蝶', url: 'http://172.16.20.72:6700/src/assets/images/photo/8.png', x: 300, y: 450},
  {id: 9, name: '鱼儿', url: 'http://172.16.20.72:6700/src/assets/images/photo/9.png', x: 500, y: 500},
];

// 存储加载的图片和点击检测数据
const loadedImages = ref([]);
const hitCanvas = ref(null);
const hitCtx = ref(null);

// 创建点击检测 Canvas
function createHitCanvas() {
  hitCanvas.value = document.createElement('canvas');
  hitCanvas.value.width = 1600;
  hitCanvas.value.height = 900;
  hitCtx.value = hitCanvas.value.getContext('2d');
}

// 从服务器加载图片
async function loadImageFromServer(imageData) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = "anonymous"; // 处理跨域问题

    img.onload = () => {
      console.log(`图片加载成功: ${imageData.name}`);
      resolve({
        ...imageData,
        img: img,
        width: img.naturalWidth,
        height: img.naturalHeight,
        uniqueColor: generateUniqueColor(imageData.id)
      });
    };

    img.onerror = () => {
      console.error(`图片加载失败: ${imageData.url}`);
      reject(new Error(`Failed to load image: ${imageData.url}`));
    };

    img.src = imageData.url;
  });
}

// 生成唯一颜色
function generateUniqueColor(id) {
  const colors = [
    '#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF',
    '#00FFFF', '#FF8000', '#8000FF', '#00FF80', '#FF0080'
  ];
  return colors[id % colors.length];
}

// 绘制图片到主 Canvas
function drawImageToMainCanvas(image) {
  ctx.drawImage(image.img, image.x, image.y, image.width, image.height);

  // 可选：绘制边框和文字标识
  ctx.strokeStyle = 'rgba(255, 255, 255, 0.5)';
  ctx.lineWidth = 2;
  ctx.strokeRect(image.x, image.y, image.width, image.height);

  ctx.fillStyle = 'white';
  ctx.font = '14px Arial';
  ctx.fillText(image.name, image.x, image.y - 5);
}

// 绘制图片到点击检测 Canvas
function drawImageToHitCanvas(image) {
  hitCtx.value.fillStyle = image.uniqueColor;

  // 创建图片的轮廓路径（模拟不规则形状）
  createIrregularShape(hitCtx.value, image.x, image.y, image.width, image.height);
  hitCtx.value.fill();
}

// 创建不规则形状（根据你的图片形状调整）
function createIrregularShape(ctx, x, y, width, height) {
  ctx.beginPath();

  // 示例：创建一个星形路径（根据你的实际图片调整）
  const centerX = x + width / 2;
  const centerY = y + height / 2;
  const outerRadius = Math.min(width, height) / 2;
  const innerRadius = outerRadius / 2;
  const spikes = 5;

  for (let i = 0; i < spikes * 2; i++) {
    const radius = i % 2 === 0 ? outerRadius : innerRadius;
    const angle = (Math.PI * 2 * i) / (spikes * 2);
    const pointX = centerX + Math.cos(angle) * radius;
    const pointY = centerY + Math.sin(angle) * radius;

    if (i === 0) {
      ctx.moveTo(pointX, pointY);
    } else {
      ctx.lineTo(pointX, pointY);
    }
  }

  ctx.closePath();
}

// 精确的像素检测（处理透明PNG）
function setupPixelPerfectHitDetection(image) {
  // 创建临时 Canvas 处理图像透明度
  const tempCanvas = document.createElement('canvas');
  const tempCtx = tempCanvas.getContext('2d');
  tempCanvas.width = image.width;
  tempCanvas.height = image.height;

  // 绘制原图到临时 Canvas
  tempCtx.drawImage(image.img, 0, 0);

  // 获取图像数据
  const imageData = tempCtx.getImageData(0, 0, image.width, image.height);
  const data = imageData.data;

  // 创建点击掩模
  const maskData = hitCtx.value.createImageData(image.width, image.height);

  for (let i = 0; i < data.length; i += 4) {
    const alpha = data[i + 3];

    if (alpha > 10) { // 非透明像素
      const rgb = hexToRgb(image.uniqueColor);
      maskData.data[i] = rgb.r;     // R
      maskData.data[i + 1] = rgb.g; // G
      maskData.data[i + 2] = rgb.b; // B
      maskData.data[i + 3] = 255;   // A
    } else {
      // 透明区域保持透明
      maskData.data[i + 3] = 0;
    }
  }

  // 在点击检测 Canvas 上绘制掩模
  hitCtx.value.putImageData(maskData, image.x, image.y);
}

// 十六进制颜色转RGB
function hexToRgb(hex) {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : {r: 0, g: 0, b: 0};
}

// 处理点击事件
function handleCanvasClick(event) {
  const rect = myCanvas.value.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;

  // 获取点击检测 Canvas 上该位置的颜色
  const pixel = hitCtx.value.getImageData(x, y, 1, 1).data;

  if (pixel[3] === 0) {
    console.log('点击了空白区域');
    return;
  }

  const color = `#${((1 << 24) + (pixel[0] << 16) + (pixel[1] << 8) + pixel[2]).toString(16).slice(1)}`;

  // 查找对应的图片
  const clickedImage = loadedImages.value.find(img =>
      img.uniqueColor.toUpperCase() === color.toUpperCase()
  );

  if (clickedImage) {
    console.log(`点击了: ${clickedImage.name}`);
    onImageClick(clickedImage, x, y);
  }
}

// 图片点击回调
function onImageClick(image, x, y) {
  // 视觉反馈：高亮被点击的图片
  highlightImage(image);

  // 显示点击信息
  showClickInfo(image, x, y);

  // 这里可以添加你的业务逻辑
  alert(`点击了 ${image.name} 图片！\n位置: (${x}, ${y})`);
}

// 高亮被点击的图片
function highlightImage(image) {
  // 保存原始状态
  const originalGlobalAlpha = ctx.globalAlpha;

  // 绘制半透明覆盖层
  ctx.fillStyle = 'rgba(255, 255, 0, 0.3)';
  ctx.fillRect(image.x, image.y, image.width, image.height);

  // 绘制边框
  ctx.strokeStyle = 'yellow';
  ctx.lineWidth = 3;
  ctx.strokeRect(image.x, image.y, image.width, image.height);

  // 恢复原始状态
  ctx.globalAlpha = originalGlobalAlpha;

  // 1秒后重绘取消高亮
  setTimeout(() => {
    redrawAllImages();
  }, 1000);
}

// 显示点击信息
function showClickInfo(image, x, y) {
  ctx.fillStyle = 'black';
  ctx.font = '16px Arial';
  ctx.fillText(`点击了: ${image.name}`, 20, 30);
  ctx.fillText(`位置: (${Math.round(x)}, ${Math.round(y)})`, 20, 60);
}

// 重新绘制所有图片
function redrawAllImages() {
  ctx.clearRect(0, 0, 1600, 900);
  loadedImages.value.forEach(image => {
    drawImageToMainCanvas(image);
  });
}

// 初始化 Canvas
async function initCanvas() {
  ctx = myCanvas.value.getContext('2d');
  createHitCanvas();

  try {
    // 加载所有图片
    const loadPromises = imageDataList.map(imageData =>
        loadImageFromServer(imageData)
    );

    const loadedImagesArray = await Promise.all(loadPromises);
    loadedImages.value = loadedImagesArray;

    // 绘制所有图片到主 Canvas
    loadedImages.value.forEach(image => {
      drawImageToMainCanvas(image);
    });

    // 设置点击检测
    loadedImages.value.forEach(image => {
      setupPixelPerfectHitDetection(image);
    });

    console.log('所有图片加载完成！');

  } catch (error) {
    console.error('图片加载失败:', error);
  }
}

// 鼠标移动效果
function handleMouseMove(event) {
  const rect = myCanvas.value.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;

  const pixel = hitCtx.value.getImageData(x, y, 1, 1).data;

  if (pixel[3] === 0) {
    myCanvas.value.style.cursor = 'default';
    return;
  }

  const color = `#${((1 << 24) + (pixel[0] << 16) + (pixel[1] << 8) + pixel[2]).toString(16).slice(1)}`;

  const hoveredImage = loadedImages.value.find(img =>
      img.uniqueColor.toUpperCase() === color.toUpperCase()
  );

  if (hoveredImage) {
    myCanvas.value.style.cursor = 'pointer';

    // 可选：实时显示悬停信息
    ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
    ctx.fillRect(x + 10, y - 30, 120, 25);
    ctx.fillStyle = 'white';
    ctx.font = '12px Arial';
    ctx.fillText(`悬停: ${hoveredImage.name}`, x + 15, y - 15);
  } else {
    myCanvas.value.style.cursor = 'default';
  }
}

onMounted(() => {
  initCanvas();

  // 添加事件监听器
  myCanvas.value.addEventListener('click', handleCanvasClick);
  myCanvas.value.addEventListener('mousemove', handleMouseMove);
});
</script>

<style scoped lang="less">
.root {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

  .center_box {
    width: 1600px;
    height: 900px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #2c3e50;
    border-radius: 10px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);

    .canvas_box {
      width: 1600px;
      height: 900px;
      position: relative;

      #myCanvas {
        width: 100%;
        height: 100%;
        border-radius: 8px;
      }
    }
  }
}
</style>
